package com.javaEE.tes.controllers;

import com.javaEE.tes.dao.AssociationRepository;
import com.javaEE.tes.dao.dto.StudentAssociation;
import com.javaEE.tes.entities.Association;
import com.javaEE.tes.entities.Student;
import com.javaEE.tes.entities.Teacher;
import com.javaEE.tes.services.AssociationService;
import com.javaEE.tes.services.StudentService;
import com.javaEE.tes.services.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("association")
public class AssociationControllers {

    @Autowired
    AssociationService associationService;
    @Autowired
    StudentService studentService;
@Autowired
    TeacherService teacherService;

    @GetMapping
    public String displayAssociation(Model model){

        List<StudentAssociation> associations = associationService.studentAssociation();
        model.addAttribute("association",associations);

        return "association/list-association";
    }

    @GetMapping("/new")
    public String displayAssociationFrom(Model model){
        Association aAssociation = new Association();
        List<Teacher> teachers = teacherService.getAll();
        model.addAttribute("association",aAssociation);
        model.addAttribute("teacher",teachers);
        return "association/new-association";
    }
    @PostMapping("/save")
    public String createAssociation(Model model, @Valid Association association, Errors errors){

        List<Teacher> teachers = teacherService.getAll();
        model.addAttribute("teacher",teachers);
        if (errors.hasErrors()) return "association/new-association";
        associationService.save(association);
        return "redirect:/association";
    }
}
